using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rotempco.Core.ORM.Objects;
using System.Reflection;

namespace Rotempco.Core.ORM.Logic
{
    public static class PMLExtensions
    {
        public static string PMLToDBString(this PML pml)
        {
            return string.Join(Environment.NewLine, pml.Lines);
        }

        public static PML DBStringToPML(string dbString)
        {
            return new PML(dbString.Split(Environment.NewLine.ToCharArray()));
        }

        public static PML ToPML<TSource>(TSource source)
        {
            if (source == null)
                return new PML();

            Type destinationType = typeof(TSource);
            PropertyInfo[] sourceFields = source.GetType().GetProperties();

            List<string> propertyList = new List<string>();

            foreach (PropertyInfo sourceField in sourceFields)
            {
                PropertyInfo destinationField = destinationType.GetProperty(sourceField.Name);

                object value = sourceField.GetValue(source, null);

                propertyList.Add(sourceField.Name + " : " + value);
            }

            return new PML(propertyList.ToArray());
        }
    }
}
